package com.interview.score.controller;

import com.interview.score.common.Result;
import com.interview.score.common.ResultMessage;
import com.interview.score.common.StatusCode;
import com.interview.score.entity.ExaminerDrawLots;
import com.interview.score.entity.PsdStrategy;
import com.interview.score.entity.ScoreElement;
import com.interview.score.service.DataExchangeService;
import com.interview.score.service.ExamRoomService;
import com.interview.score.utils.RedisKeyUtils;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/downLoad")
public class DownLoadController {

    @Autowired
    private Environment environment;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DataExchangeService dataExchangeService;
    @Autowired
    private ExamRoomService examRoomService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisKeyUtils redisKeyUtils;



    @PostMapping("downLoadExameeDrawLotsSummary")
    public Result downLoadExameeDrawLotsSummary() {
        //校验是否为空
        String examRoomId = examRoomService.getExamRoomId();
        String groupId=examRoomId.replaceAll("\\s*","").replaceAll("[^(A-Z)]","");

        Map map = dataExchangeService.downLoadExameeDrawLotsSummary(groupId);
        //获取考场总人数信息和缺考信息
        examRoomService.setTotalExameeAmount(Integer.parseInt((String) map.get(environment.getProperty("TotalExameeAmountKey"))));
        //设置缺考人员信息
        String absentSequence_s=(String)map.get(environment.getProperty("AbsentSequenceKey"));
        String[] letter = absentSequence_s.split(",");
        int[] absentSequence_i = new int[letter.length];
        for (int i = 0; i < absentSequence_i.length; i++) {
            absentSequence_i[i] = Integer.parseInt(letter[i]);
        }
        examRoomService.setAbsentSequence(absentSequence_i);
        return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS);
    }

    @PostMapping("downLoadExaminerDrawLotsInfo")
    public Result downLoadExaminerDrawLotsInfo() {
        String examRoomId = examRoomService.getExamRoomId();
        String examRoomCode = redisKeyUtils.getExamRoomCodeFromExamRoomId(examRoomId);
        List<ExaminerDrawLots> examinerDrawLots=dataExchangeService.downLoadExaminerDrawLotsInfoByExamRoomCode(examRoomCode);
        //获取密码策略，生成密码
        PsdStrategy psdStrategy=dataExchangeService.getAvailablePasswordGenerationStrategy();
        //组装Key
        //获取考场Id
        String key=environment.getProperty("ExaminerIdNumbersKey")+"-"+examRoomId;
        for (ExaminerDrawLots examinerDrawLot : examinerDrawLots) {
            String idNumber = examinerDrawLot.getIdNumber();
            //将ID存成主键
            redisTemplate.opsForSet().add(key, idNumber);
        }

        for (ExaminerDrawLots examinerDrawLot : examinerDrawLots) {
            String idNumber = examinerDrawLot.getIdNumber();
            String passWord = generatePassWord(idNumber, psdStrategy.getId());
            String name = examinerDrawLot.getName();
            String signState = examinerDrawLot.getSignState();
            String seatNumber = examinerDrawLot.getSeatNumber();
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put(environment.getProperty("PassWordField"), passWord);
            hashMap.put(environment.getProperty("NameField"), name);
            hashMap.put(environment.getProperty("SignStateField"), signState);
            hashMap.put(environment.getProperty("SeatNumberField"), seatNumber);
            redisTemplate.opsForHash().putAll(environment.getProperty("ExaminerDetailsKey")+"-"+examRoomId+"-"+idNumber,hashMap);
        }

        //存入redis
        return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS);
    }

    @PostMapping("downLoadScoreElement")
    public Result downLoadScoreElement() {
        String examRoomId = examRoomService.getExamRoomId();
        List<ScoreElement> scoreElements = dataExchangeService.downLoadScoreElementList();
        String scoreElementIdsKey = redisKeyUtils.spliceTwoRedisKey("ScoreElementIdsKey", examRoomId);
        //获取ID
        for (ScoreElement scoreElement : scoreElements) {
            String id = scoreElement.getId();
            //将ID存成主键
            redisTemplate.opsForSet().add(scoreElementIdsKey, id);
        }
        //存储评分明细
        for (ScoreElement scoreElement : scoreElements) {
            String id = scoreElement.getId();
            String name = scoreElement.getName();
            String excellentScore = scoreElement.getExcellentScore();
            String fullScore = scoreElement.getFullScore();
            String mediumScore = scoreElement.getMediumScore();
            String poorScore = scoreElement.getPoorScore();
            String goodScore = scoreElement.getGoodScore();
            HashMap<String, String> map = new HashMap<>();
            map.put(environment.getProperty("NameHash"), name);
            map.put(environment.getProperty("FullScoreHash"), fullScore);
            map.put(environment.getProperty("ExcellentScoreHash"), excellentScore);
            map.put(environment.getProperty("MediumScoreHash"), mediumScore);
            map.put(environment.getProperty("GoodScoreHash"), goodScore);
            map.put(environment.getProperty("PoorScoreHash"), poorScore);
            redisTemplate.opsForHash().putAll(redisKeyUtils.spliceThreeRedisKey("ScoreElementDetailsKey",examRoomId,id),map);
        }

        return new Result(true,StatusCode.OK,ResultMessage.OPERATION_SUCCESS,scoreElements);
    }

    private String generatePassWord(String idNumber, String strategyId) {
        String last_sixPassWord = idNumber.substring(idNumber.length() - 6);
        String finalPassWord = "";
        switch (strategyId){
            case "last_six":
                finalPassWord= last_sixPassWord;
                break;
            case "last_six_reverse":
                StringBuilder sb = new StringBuilder(last_sixPassWord);
                finalPassWord = sb.reverse().toString();
                break;
            case "last_six_plus_100000":
                String first = last_sixPassWord.substring(0, 1);
                int firstResult = Integer.parseInt(first) + 1;
                finalPassWord= firstResult+last_sixPassWord.substring(1);
                break;
            case "last_six_plus_200000":
                String temp = last_sixPassWord.substring(0, 1);
                int temp_int = Integer.parseInt(temp) + 1;
                finalPassWord= temp_int+last_sixPassWord.substring(1);
                break;
            default:
                finalPassWord = last_sixPassWord;
        }
        return finalPassWord;
    }
}
